<template>
  <div class="page">
    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="负责人：">
          <el-select v-model="formInline.principal" filterable clearable>
            <el-option v-for="(item,index) in userList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止月份：">
          <el-date-picker v-model="formInline.statEndTime" type="month" placeholder="选择月" value-format="yyyy-MM">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="onSearch()">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="small" @click="openCollectDialog('收款变动',4)">收款变动</el-button>
        <!-- <el-button type="primary" size="small" @click="openCollectDialog('错误金额修正',7)">错误金额修正</el-button> -->
        <!-- <el-button type="default" size="small" @click="downloadExcel" :loading="eloading">导出筛选结果</el-button> -->
        <auth-button uid="1040301" type="default" size="small" @click.native="downloadExcel" :loading="eloading">导出筛选结果</auth-button>
      </div>
      <!-- 操作区域 end -->

      <el-table ref="elTable" class="el_table" size="small" :data="tableData" show-summary :summary-method="summaryMethod" @sort-change="sortChange">
        <el-table-column prop="channelName" label="客户信息" width="150px">
          <template slot-scope="{row}">
            <tab-user :user="userFormatter(row)"></tab-user>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalName" label="预约医院" show-overflow-tooltip width="160" />
        <el-table-column prop="appointmentTime" label="预约时间" sortable="custom" show-overflow-tooltip width="120">
          <template slot-scope="{row}">{{showTime(row.appointmentTime)}}</template>
        </el-table-column>
        <el-table-column prop="firstCollectTime" label="首次成交" sortable="custom" show-overflow-tooltip width="120">
          <template slot-scope="{row}">{{showTime(row.firstCollectTime)}}</template>
        </el-table-column>
        <el-table-column prop="principal" label="负责人" show-overflow-tooltip />
        <el-table-column prop="totalDealAmount" label="总成交" show-overflow-tooltip />
        <el-table-column prop="totalCollectMoney" label="总收款" show-overflow-tooltip />
        <el-table-column v-for="(item,index) in monthList" :key="index" :prop="`month${index+1}Collect`" :label="`${item}月收款`" show-overflow-tooltip :fixed="index == monthList.length-1?'right':false" width="120" />
        <!-- <el-table-column prop="month2Collect" label="4月收款" show-overflow-tooltip />
        <el-table-column prop="month3Collect" label="5月收款" show-overflow-tooltip />
        <el-table-column prop="month4Collect" label="6月收款" show-overflow-tooltip />
        <el-table-column prop="month5Collect" label="7月收款" show-overflow-tooltip />
        <el-table-column prop="month6Collect" label="8月收款" show-overflow-tooltip /> -->
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize" :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList" @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

  </div>
</template>

<script>
import {
  showToast,
  showModal,
  deepClone,
  broadcast,
  received,
} from "@/common/util";
import { exportExcel } from "@/common/common";
import GlsxDialog from "@/components/Dialog/index";
import moment from "moment";
import TabUser from "@/components/user";
import { GETDEALBUSINESSSEARCH, DEALBUSINESSEXPORT } from "@/http/deal";
import { GETUSEROPTIONS } from "@/http/system";
import AuthButton from "@/components/auth-button";
export default {
  components: {
    GlsxDialog,
    TabUser,
    AuthButton,
  },
  data() {
    return {
      formInline: {},
      tableData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 50, 100],
      pageSize: 20,
      orderTime: [],
      orderTime2: [],
      showDialog: false,
      loading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "前天",
            onClick(picker) {
              const end = moment().subtract(2, "days").format("YYYY-MM-DD");
              const start = moment().subtract(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = moment().subtract(1, "days").format("YYYY-MM-DD");
              const start = moment().subtract(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "今天",
            onClick(picker) {
              const end = moment().subtract(0, "days").format("YYYY-MM-DD");
              const start = moment().subtract(0, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "明天",
            onClick(picker) {
              const end = moment().add(1, "days").format("YYYY-MM-DD");
              const start = moment().add(1, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "后天",
            onClick(picker) {
              const end = moment().add(2, "days").format("YYYY-MM-DD");
              const start = moment().add(2, "days").format("YYYY-MM-DD");
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      eloading: false,
      monthList: [],
      userList: [],
      summary: [],
    };
  },
  created() {
    this.initMonth();
    this.getUser();
  },
  mounted() {
    this.getList();
    received("commom.edit.success", this.getList);
  },
  methods: {
    /** 重置 */
    rest() {
      this.formInline = {};
      this.orderTime = [];
      this.initMonth();
      this.getList();
    },

    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let oParams = JSON.parse(JSON.stringify(this.formInline));
      oParams.pageNumber = this.pageNumber;
      oParams.pageSize = this.pageSize;
      return oParams;
    },

    /** 获取列表 */
    getList() {
      let _this = this;
      let oParams = this.getParams();
      if (oParams.statEndTime) {
        _this.initMonth(oParams.statEndTime);
      }
      GETDEALBUSINESSSEARCH(oParams).then((res) => {
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
        _this.summary = res.summary || [];
      });
    },

    // 格式化处理用户信息
    userFormatter(row) {
      let o = deepClone(row);
      o.customerName = o.name;
      o.customerPhone = o.phone;
      o.id = o.clueId;
      return o;
    },

    // 监听组件变化
    onChange(e) {
      if (e.id) {
        this[e.id] = false;
      }
    },

    // 导出excel
    downloadExcel() {
      let _this = this;
      let o = deepClone(_this.formInline);
      let m = Object.keys(o);
      if (m.length > 0) {
        showModal({
          message: "确定是否导出筛选条件下面所有业绩核算?",
          showCancelButton: true,
          type: "warning",
          success: function () {
            _this.dowloadExcelFile();
          },
        });
        return false;
      }
      showToast({
        message: "请选择筛选条件后再导出",
      });
    },

    // 下载excel
    dowloadExcelFile() {
      let _this = this;
      let oParams = this.getParams();
      let options = {};
      options.method = "GET";
      options.data = oParams;
      options.url = DEALBUSINESSEXPORT;
      options.fileName = "业绩核算.xlsx";
      _this.eloading = true;
      exportExcel(options).then((res) => {
        _this.eloading = false;
      });
    },

    // 初始化月份
    initMonth(str) {
      let month = Number(moment().format("M"));
      if (str) {
        month = Number(moment(str).format("M"));
      }
      console.log(month);
      let min = month - 5 < 0 ? 12 + month - 5 : month - 5;
      console.log(min);
      let arr = [];
      for (var i = 0; i < 6; i++) {
        if (min + i > 12) {
          arr.push(min + i - 12);
        } else {
          arr.push(min + i);
        }
      }
      this.monthList = arr;
    },

    // 获取负责人列表
    getUser(name) {
      GETUSEROPTIONS({ username: name }).then((res) => {
        this.userList = res.data || [];
      });
    },

    // 打开收款变动
    openCollectDialog(title, status) {
      broadcast("customer.collect.add", { status: status, title: title });
    },
    // 格式化展示时间
    showTime(str) {
      if (!str) {
        return "";
      }
      return moment(str).format("yyyy-MM-DD HH:mm");
    },

    // 自定义合计
    summaryMethod(e) {
      let { columns, data } = e;
      let sums = [];
      let m = this.summary;
      let ids = ['month1Collect','month2Collect','month3Collect','month4Collect','month5Collect','month6Collect','totalCollectMoney','totalDealAmount'];
      columns.forEach((item, index) => {
        if (index == 0) {
          sums[index] = "合计";
          return;
        }

        if(ids.indexOf(item.property)>=0){
          sums[index] = m[item.property]
        }else{
          sums[index] = ''
        }
      });

      return sums;
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      this.formInline.orderField = prop;
      if (order == "ascending") {
        this.formInline.orderDirection = "ASC";
      } else {
        this.formInline.orderDirection = "DESC";
      }
      this.getList()
    },

    // 搜索
    onSearch(){
      this.pageNumber = 1;
      this.getList()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/style/customer/index.scss";
</style>
